package com.sdp.wx.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdp.core.bizc.db.Query;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.core.bizc.vo.DataCenter;
import com.sdp.core.bizc.vo.Result;
import com.sdp.flow.db.entity.ActHiComment;
import com.sdp.flow.db.service.IWorkflowService;
import com.sdp.flow.dto.FlowParam;
import com.sdp.flow.utils.FlowConstants;
import com.sdp.wx.db.wx_emp_ask_forLeave.entity.WxEmpAskForleave;
import com.sdp.wx.db.wx_emp_ask_forLeave.service.IWxEmpAskForleaveService;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.WxConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsp
 * @since 2024-02-21
 */
@RestController
@RequestMapping("/WxEmpAskForleaveController")
public class WxEmpAskForleaveController {
    @Autowired
    private IWxEmpAskForleaveService iWxEmpAskForleaveService;
    @Autowired
    private IWorkflowService workflowService;
    @Autowired
    private CurrentLoginEmp currentLoginEmp;
    @Autowired
    private Query query;
    @PostMapping(value = "/page")
    public Result<?> page(@RequestBody DataCenter dataCenter) {
        return Result.ok(query.page(iWxEmpAskForleaveService, WxEmpAskForleave.class, dataCenter));
    }

    @PostMapping(value = "/save")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> save(@RequestBody WxEmpAskForleave wxEmpAskForleave) {
        if(wxEmpAskForleave==null) {
            return Result.error("员工请假申请为空");
        }
        JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
        if(StringUtils.isEmpty(wxEmpAskForleave.getKeyId())) {
            wxEmpAskForleave.setKeyId("");
            wxEmpAskForleave.setCreateTime(LocalDateTime.now());
            wxEmpAskForleave.setIsFinish(WxConstants.否.getCode());
            wxEmpAskForleave.setApprovalState(WxConstants.流程审批状态_未提交.getCode());
            wxEmpAskForleave.setApplicationEmpNo(emp.getString("empNo"));
            wxEmpAskForleave.setApplicationEmpName(emp.getString("empName"));
            iWxEmpAskForleaveService.save(wxEmpAskForleave);
        }else{
            iWxEmpAskForleaveService.updateById(wxEmpAskForleave);
        }

        return Result.ok();
    }

    @PostMapping(value = "/saveAndStartFlow")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> saveAndStartFlow(@RequestBody WxEmpAskForleave wxEmpAskForleave) {
        if(wxEmpAskForleave==null) {
            return Result.error("员工请假申请为空");
        }
        Result<?> r = ApplicationContextUtils.getBean(WxEmpAskForleaveController.class).save(wxEmpAskForleave);
        if(r==null || !r.isSuccess()) {
            return r;
        }
        JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
        // 如果请假超过一天并且是事假，走不超过一天流程，否则走超过一天流程
        BigDecimal bigDecimal=new BigDecimal(wxEmpAskForleave.getAskDay());
        BigDecimal bigDecimal1=new BigDecimal("1");
        if(bigDecimal.compareTo(bigDecimal1)<=1&&WxConstants.事假.getCode().equals(wxEmpAskForleave.getAskType())){
            wxEmpAskForleave.setTemplateId(WxConstants.事假不超过一天流程模版.getCode());
        }else{
            wxEmpAskForleave.setTemplateId(WxConstants.事假超过一天及其他类型请假流程模版.getCode());
        }
        //设置审批状态
        wxEmpAskForleave.setApprovalState(WxConstants.流程审批状态_审批中.getCode());

        //发起流程
        FlowParam flowParam = new FlowParam();
        flowParam.setUserId(emp.getString("empNo"));
        flowParam.setTemplateId(wxEmpAskForleave.getTemplateId());
        flowParam.setBizId(wxEmpAskForleave.getKeyId());

        //指定审批人
        Map<String, Object> variableMap = new HashMap<>();
        BusinessContext businessContext = new BusinessContext();
        businessContext.put(WxEmpAskForleave.class, wxEmpAskForleave);
        variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, wxEmpAskForleave.getApprover());
        variableMap.put(WxConstants.流程监听器中执行的类.getCode(), "com.sdp.wx.controller.WxEmpAskForleaveController");
        variableMap.put(WxConstants.流程监听器中执行类的方法.getCode(), "flowCommitListener");
        variableMap.put(WxConstants.流程监听器中执行类的方法的参数.getCode(), businessContext);
        flowParam.setVariableMap(variableMap);


        String instanceId = workflowService.startFlowAndCommit(flowParam);
        if (StringUtils.isEmpty(instanceId)) {
            return Result.error("流程启动失败!");
        }

        //发起成功设置流程实例Id
        wxEmpAskForleave.setInstanceId(instanceId);
        iWxEmpAskForleaveService.updateById(wxEmpAskForleave);
        return Result.ok(wxEmpAskForleave);
    }
    /**
     * 流程提交
     * @param wxEmpAskForleave
     * @return
     */
    @PostMapping(value = "/commit")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> commit(@RequestBody WxEmpAskForleave wxEmpAskForleave) {
        if(wxEmpAskForleave == null) {
            return Result.error("员工请假申请为空");
        }
        if (StringUtils.isEmpty(wxEmpAskForleave.getKeyId())) {
            return Result.error("员工请假申请为空内码为空");
        }

        JSONObject emp = currentLoginEmp.getCurrentEmpInfo();
        //提交流程
        if (StringUtils.isEmpty(wxEmpAskForleave.getTaskId())) {
            return Result.error("员工请假申请审批信息不完整");
        }
        FlowParam flowParam = new FlowParam();
        flowParam.setUserId(emp.getString("empNo"));

        flowParam.setTaskId(wxEmpAskForleave.getTaskId());
        if (!StringUtils.isEmpty(wxEmpAskForleave.getIsPass())) {
            Map<String, Object> variableMap = new HashMap<>();
            variableMap.put("isPass", wxEmpAskForleave.getIsPass());
            variableMap.put("link", wxEmpAskForleave.getLink());
            variableMap.put("userName", emp.getString("empName"));
            variableMap.put("userAvatar", emp.getString("profilePicture"));
            variableMap.put("userSign", emp.getString("nameSign"));
            BusinessContext businessContext = new BusinessContext();
            businessContext.put(WxEmpAskForleave.class, wxEmpAskForleave);

            String currentNode = workflowService.getCurrentNode(wxEmpAskForleave.getTaskId());
            if((WxConstants.是.getCode().equals(wxEmpAskForleave.getIsPass()) && ( WxConstants.事假不超过一天_部门领导审批.getCode().equals(currentNode))||WxConstants.事假超过一天及其他类型请假_劳资审批.getCode().equals(currentNode))||(FlowConstants.flow_end_value.equals(wxEmpAskForleave.getLink()))) {
                //如果节信息是结束
                //或者最后一个环节，没有环节信息，并且是同意通过
                variableMap.put(WxConstants.流程监听器中执行的类.getCode(), "com.sdp.wx.controller.WxEmpAskForleaveController");
                variableMap.put(WxConstants.流程监听器中执行类的方法.getCode(), "flowEndListener");
            }else {
                variableMap.put(WxConstants.流程监听器中执行的类.getCode(), "com.sdp.wx.controller.WxEmpAskForleaveController");
                variableMap.put(WxConstants.流程监听器中执行类的方法.getCode(), "flowCommitListener");
            }
            variableMap.put(WxConstants.流程监听器中执行类的方法的参数.getCode(), businessContext);

            if (WxConstants.否.getCode().equals(wxEmpAskForleave.getIsPass())) {
                variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, wxEmpAskForleave.getApplicationEmpNo());
                if(StringUtils.isEmpty(wxEmpAskForleave.getApprovalOpinion())){
                    wxEmpAskForleave.setApprovalOpinion("不同意");
                }
                wxEmpAskForleave.setApprovalState(WxConstants.流程审批状态_驳回.getCode());
            }else {
                if(StringUtils.isEmpty(wxEmpAskForleave.getApprovalOpinion()) && !WxConstants.事假不超过一天_个人申请节点.getCode().equals(currentNode)&&!WxConstants.事假超过一天及其他类型请假_个人申请节点.getCode().equals(currentNode)){
                    wxEmpAskForleave.setApprovalOpinion("同意");
                }
                variableMap.put(FlowConstants.FLOW_ASSIGN_PERSON_KEY, wxEmpAskForleave.getApprover());
                wxEmpAskForleave.setApprovalState(WxConstants.流程审批状态_审批中.getCode());
            }

            flowParam.setVariableMap(variableMap);

            //更新审批人列表
            if(!WxConstants.事假不超过一天_个人申请节点.getCode().equals(currentNode) && !WxConstants.事假超过一天及其他类型请假_个人申请节点.getCode().equals(currentNode)){
                wxEmpAskForleave.setApproversList((wxEmpAskForleave.getApproversList()==null?"":wxEmpAskForleave.getApproversList())+("["+emp.getString("empNo")+"]"));
            }
        }
        if (!StringUtils.isEmpty(wxEmpAskForleave.getApprovalOpinion())) {
            flowParam.setOpinion(wxEmpAskForleave.getApprovalOpinion());
        }
        iWxEmpAskForleaveService.updateById(wxEmpAskForleave);
        workflowService.commitTask(flowParam);
        return Result.ok();
    }
    /**
     * 审批结束后，更改审批状态
     * @param businessContext
     */
    @Transactional(rollbackFor=Exception.class)
    public void flowEndListener(BusinessContext businessContext)  {
        WxEmpAskForleave wxEmpAskForleave = businessContext.get(WxEmpAskForleave.class);
        if(wxEmpAskForleave!=null && WxConstants.是.getCode().equals(wxEmpAskForleave.getIsPass())) {
            wxEmpAskForleave.setApprovalState(WxConstants.流程审批状态_审批通过.getCode());
            iWxEmpAskForleaveService.updateById(wxEmpAskForleave);
        }
    }
    public void flowCommitListener(BusinessContext businessContext) {

    }

    @RequestMapping(value="/queryByInstanceId")
    public Result<?> queryByInstanceId(@RequestParam String instanceId) {
        if (StringUtils.isEmpty(instanceId)) {
            return Result.error("instanceId不能为空!");
        }
        QueryWrapper<WxEmpAskForleave> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WxEmpAskForleave::getInstanceId, instanceId);
        WxEmpAskForleave wxEmpAskForleave = iWxEmpAskForleaveService.getOne(queryWrapper, false);
        List<ActHiComment> commentList = workflowService.getApprovedOpinionNew(instanceId);
        wxEmpAskForleave.setApprovalOpinions(commentList);
        return Result.ok(wxEmpAskForleave);
    }
    /**
     * 流程撤销
     * @param instanceId
     * @return
     */
    @GetMapping(value = "/cancel")
    @Transactional(rollbackFor=Exception.class)
    public Result<?> cancel(@RequestParam(name="instanceId",required=true) String instanceId) {
        LambdaQueryWrapper<WxEmpAskForleave> query = new LambdaQueryWrapper<>();
        query.eq(WxEmpAskForleave::getInstanceId, instanceId);
        WxEmpAskForleave wxEmpAskForleave = iWxEmpAskForleaveService.getOne(query);
        if(wxEmpAskForleave==null) {
            return Result.error("员工请假申请信息不存在，不能进行撤销");
        }
        JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
        if(!wxEmpAskForleave.getApplicationEmpNo().equals(emp.getString("empNo"))) {
            return Result.error("不是提交人，不能进行撤销操作");
        }

        //流程撤销
        workflowService.stopFlow(instanceId, "撤销");
        //删除员工请假申请
        iWxEmpAskForleaveService.removeById(wxEmpAskForleave.getKeyId());
        return Result.ok();
    }
}

